package com.wqz.day.day.up.queue;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 实现一个队列，存放已经初始化好的
 *
 * @author wuqz
 * @date 2024/3/7
 */
@Slf4j
public class WebDriverQueue {
    private String name;

    /**
     * 存放队列
     */
    private BlockingQueue<DecorationWebDriver> queue;

    private Integer maxSize;


    public WebDriverQueue(String name, int maxSize, ChromeOptions chromeOptions) {
        if (maxSize != 0) {
            this.queue = new LinkedBlockingQueue<>(maxSize);
            this.maxSize = maxSize;
            this.name = name;

            //初始化webDriver
            for (int i = 0; i < this.maxSize; i++) {
                String uuid = IdUtil.fastUUID();
                WebDriver webDriver = new ChromeDriver(chromeOptions);

                DecorationWebDriver decorationWebDriver = new DecorationWebDriver(uuid, webDriver);
                enqueue(decorationWebDriver);
            }
        }
    }

    /**
     * 进队
     * @param decorationWebDriver
     * @throws InterruptedException
     */
    public void enqueue(DecorationWebDriver decorationWebDriver){
        queue.offer(decorationWebDriver);
        log.info("队列{}，对象[{}]入队成功！", this.name, decorationWebDriver.getId());
    }

    /**
     * 出队
     * @return
     * @throws InterruptedException
     */
    public DecorationWebDriver dequeue() throws InterruptedException{
        DecorationWebDriver webDriver = queue.take();
        log.info("队列{}，对象[{}]出队成功！", this.name, webDriver.getId());
        return webDriver;
    }

    public void destory() {
        if (queue != null) {
            log.info("队列WebDriverQueue：{}执行销毁方法------", name);
            try {
                for (int index = 1; index <= maxSize; index++){
                    DecorationWebDriver webDriver = queue.take();
                    if (webDriver != null) {
                        webDriver.getWebDriver().quit();
                        log.info("队列{}，对象[{}]销毁成功！", this.name, webDriver.getId());
                    }
                }
            } catch (InterruptedException e) {
                log.error("队列WebDriverQueue：{}执行销毁方法异常！------", name);
            }
        }
    }
}
